let pageSize = 5;
let page = 1;
const creator = $.cookie("teacherName");
let totalData = 0;
const loader = document.getElementById('compact-loader');
//展示教案信息
function showByPage(){
    $.ajax({
        url:"/LessonPlanManagement/ShowByPage",
        type:"get",
        dateType:"json",
        data:{
            page,
            pageSize,
            creator
        },
        success:function(res){
            // console.log(page)
            // console.log(pageSize)
            // console.log(res)
            const arr = res.data;
            //加载数据
            $(".tbody").empty();
            for (let i = 0; i < arr.length; i++) {
                $(".tbody").append(`
                    <tr>
                        <td>${arr[i].id}</td>
                        <td>${arr[i].name}</td>
                        <td>${arr[i].createtime}</td>
                        <td>${arr[i].creator}</td>
                        <td>${arr[i].note}</td> 
                        <td>
                            <a href="${arr[i].word}" class="action-btn download-btn" title="下载">
                                <i class="fas fa-download"></i> 下载
                            </a>
                            <button class="action-btn preview-btn" data-id="${arr[i].id}" title="预览">
                                <i class="fas fa-eye"></i> 预览
                            </button>
                            <button class="action-btn generateExam-btn" data-id="${arr[i].id}" title="生成试卷">
                                <i class="fas fa-file-alt"></i> 生成试卷
                            </button>
                            <button class="action-btn delete-btn" data-id="${arr[i].id}" title="删除">
                                <i class="fas fa-trash-alt"></i> 删除
                            </button>
                        </td>
                    </tr>
                `);
            }

        },
        error:function(){
            alert("展示教案信息出错，请联系管理员")
        }
    })
}

showByPage();



//展示页码
function getCount(){
    $.ajax({
        url: "/LessonPlanManagement/GetLessonPlanCount",
        type: "get",
        dataType: "json",
        data: {
            creator
        },
        success:function(res){
            // console.log(res)
            totalData = res.data
            const num = res.data
            // const pageCount = (num/pageSize)+1;
            // console.log(pageCount)
            $(".page-number").empty()
            for (let j = 1; j <= Math.ceil(num / pageSize); j++) {
                if (j === 1) {
                    // 总是显示第一页按钮
                    $(".page-number").append(`<button class="page-btn ${j === page ? 'active' : ''}" id="${j}">${j}</button>`);
                    continue;
                }

                // 显示最后一页按钮
                if (j === Math.ceil(num / pageSize)) {
                    $(".page-number").append(`<button class="page-btn ${j === page ? 'active' : ''}" id="${j}">${j}</button>`);
                    continue;
                }

                // 当前页附近显示（前后各2页）
                if (j >= page - 2 && j <= page + 2) {
                    $(".page-number").append(`<button class="page-btn ${j === page ? 'active' : ''}" id="${j}">${j}</button>`);
                    continue;
                }

                // 在第一页后添加省略号（如果当前页离第一页较远）
                if (j === 2 && page - 2 > 2) {
                    $(".page-number").append(`<span>...</span>`);
                    continue;
                }

                // 在最后一页前添加省略号（如果当前页离最后一页较远）
                if (j === Math.ceil(num / pageSize) - 1 && page + 2 < Math.ceil(num / pageSize) - 1) {
                    $(".page-number").append(`<span>...</span>`);
                    continue;
                }
            }
        },
        error(){
            alert("获取教案数量出错，请联系管理员")
        }
    })
}
getCount();


//点击页码进行切换
$(".page-number").on("click",".page-btn",function (){
    // alert(1)
    page = Number($(this).text());
    // alert(Number($(this).text()))
    $(".page-btn").removeClass("active");
    $(this).addClass("active");
    showByPage();
})

// 点击上一页
$(".front").on("click", function() {
    if (page > 1) {
        page = page - 1;
        updateActivePage(); // 更新活动页样式
        showByPage();
    }
});

// 点击下一页
$(".next").on("click", function() {
    if (page < Math.ceil(totalData / pageSize)) {
        page = page + 1;
        updateActivePage(); // 更新活动页样式
        showByPage();
    }
});

// 点击首页
$(".first").on("click", function() {
    page = 1;
    updateActivePage(); // 更新活动页样式
    showByPage();
});

// 点击尾页
$(".end").on("click", function() {
    page = Math.ceil(totalData / pageSize); // 修正尾页计算方式
    updateActivePage(); // 更新活动页样式
    showByPage();
});

//指定页码跳转
$(".change").on("click",function(){
    page = $(".page-input").val()
    updateActivePage(); // 更新活动页样式
    showByPage();
})

// 更新活动页样式的辅助函数
function updateActivePage() {
    $(".page-btn").removeClass("active"); // 移除所有页码按钮的active类
    $(`.page-btn[id="${page}"]`).addClass("active"); // 为当前页添加active类
}



//切换页最大容量
$(".page-size-select").on("change", function() {
    // location.reload()
    pageSize = Number($(this).val());
    page = 1
    // alert(pageSize);
    showByPage();
    getCount();
});



//添加教案信息
function addLessonPlan(){
    let name = $("#planName").val();
    let subiect= $("#subject").val();
    let target= $("#teachingGoal").val();
    let time = $("#classHours").val();
    let difficulty= $("#difficulty").val();
    let note= $("#remark").val();
    if (!name) {
        alert("教案名称不能为空！");
        $("#planName").focus();
        return;
    }
    if (!target) {
        alert("教学目标不能为空！");
        $("#teachingGoal").focus();
        return;
    }
    if (!note) {
        alert("备注不能为空！");
        $("#remark").focus();
        return;
    }
    loader.style.display="flex";
    setTimeout(()=>{
        sendLessonPlan(name,subiect,target,time,difficulty,note)
    },1000)

}
function sendLessonPlan(name,subject,target,time,difficulty,note){
    loader.style.opacity = '1';

    $.ajax({
        url: "/LessonPlanManagement/AddLessonPlan",
        type: "POST",
        dataType: "json",
        data: {
            name,
            target,
            note,
            time,
            difficulty,
            subject,
            creator
        },
        success: function(res) {
            // 1. 清空表单
            $("#planName, #subject, #teachingGoal, #classHours, #difficulty, #remark").val("");

            // 2. 关闭生成对话框
            generateDialog.style.display = 'none';

            // 3. 显示成功提示
            $("#success-message").text("生成教案成功");
            $(".alert-success").show().delay(1200).fadeOut();

            // 4. 刷新数据展示
            showByPage();
        },
        error: function(xhr, status, error) {
            // 显示具体错误信息（从服务器响应或状态码获取）
            let errorMsg = "教案生成失败";
            if (xhr.responseJSON && xhr.responseJSON.message) {
                errorMsg += ": " + xhr.responseJSON.message;
            } else {
                errorMsg += " (" + status + ")";
            }

            $("#error-message").text(errorMsg);
            $(".alert-danger").show().delay(1200).fadeOut();
        },
        complete: function() {
            // 无论成功失败都隐藏加载动画
            loader.style.opacity = '0';
        }
    });
}

$("#confirmGenerateBtn").on("click",function(){
    addLessonPlan()

})

$(".tbody").on("click", ".generateExam-btn", function () {
    id = $(this).data("id");
    $.cookie("lessonplanid", id);
    var name = $(this).parent().prev().prev().prev().prev().html()
    $.ajax({
        url:"/exam/GetExamByName"
        ,type:"post",
        async:false,
        data:{
            name:name,
            creator:creator
        },
        success:function(res) {
            if(res.code == 200){
                document.querySelector("#confirmModal1").style.display = "flex"
            }else{
                location.href="LessonExam"
            }
        }
        })
})
document.querySelector("#closeConfirmModal1").onclick = function (e) {
    document.querySelector(".confirmModal1").style.display = "none"
}
document.querySelector("#confirmYes1").onclick = function (e) {
    document.querySelector(".confirmModal1").style.display = "none"
}


//删除教案信息
let id;
function deleteLessonPlan(){
    $.ajax({
        url:"/LessonPlanManagement/DeleteLessonPlan",
        type:"delete",
        dataType:"json",
        data:{
            id
        },
        success:function(res){
            $("#success-message").html("已经删除教案")
            $(".alert-success").show();
            setTimeout(()=>{
                $(".alert-success").hide();
            },1200)
            showByPage();
            getCount();
        },
        error:function(){
            $("#danger-message").html("教案删除失败")
            $(".alert-danger").show();
            setTimeout(()=>{
                $(".alert-danger").hide();
            },1200)
        }
    })
}

$(".tbody").on("click",".delete-btn",function(){
    id = $(this).data("id");
   showConfirm("是否要删除该教案",function(){
       deleteLessonPlan();
   },function(){
    })
})


//点击预览加载教案详细信息
function loadDetail(){
    $.ajax({
        url:"/LessonPlanManagement/ShowLessonPlanDetail",
        type:"get",
        dataType:"json",
        data:{
            id
        },
        success:function(res){
            // console.log(res)
            let target = res.data.target
            $("#previewTeachingGoal").val(target)
        },
        error:function(){
            alert("预览操作失败青联系管理员")
        }
    })
}

$(".tbody").on("click",".preview",function(){
    $tr = $(this).closest("tr");
    id = $tr.find(".delete").data("id");
    // console.log(id)
    loadDetail()
})



//模糊搜索
let name;
$(".search-btn").on("click",function(){
    name = $(".search-lesson-plan").val();
    fuzzyQuery()
})

function fuzzyQuery(){
    $.ajax({
        url:"/LessonPlanManagement/FuzzyQueryLessonPlanByPage",
        type:"post",
        dataType:"json",
        data:{
            findByName:name,
            creator,
            page,
            pageSize
        },
        success:function(res){
            // console.log(name)
            // console.log(creator)
            // console.log(page)
            // console.log(pageSize)
            // console.log(res)
            let arr = res.data;
            //加载数据
            $(".tbody").empty();
            for (let i = 0; i < arr.length; i++) {
                $(".tbody").append(`
                    <tr>
                        <td>${arr[i].id}</td>
                        <td>${arr[i].name}</td>
                        <td>${arr[i].createtime}</td>
                        <td>${arr[i].creator}</td>
                        <td>${arr[i].note}</td> 
                        <td>
                            <a href="${arr[i].word}" class="action-btn download-btn" title="下载">
                                <i class="fas fa-download"></i> 下载
                            </a>
                            <button class="action-btn preview-btn" data-id="${arr[i].id}" title="预览">
                                <i class="fas fa-eye"></i> 预览
                            </button>
                            <button class="action-btn generateExam-btn" data-id="${arr[i].id}" title="生成试卷">
                                <i class="fas fa-file-alt"></i> 生成试卷
                            </button>
                            <button class="action-btn delete-btn" data-id="${arr[i].id}" title="删除">
                                <i class="fas fa-trash-alt"></i> 删除
                            </button>
                        </td>
                    </tr>
                `);
            }
        },
        error:function(){
            alert("查询异常，请联系管理员")
        }
    })
}


function getCountWhenSearch(){
    $.ajax({
        url:"/LessonPlanManagement/GetLessonPlanCountWhenSearch",
        type:"Post",
        dataType:"json",
        data:{
            creator,
            findByName:name,
        },
        success:function(res){
            // console.log(res)
            totalData = res.data
            const num = res.data
            // const pageCount = (num/pageSize)+1;
            // console.log(pageCount)
            $(".page-number").empty()
            for (let j = 1; j < (num/pageSize)+1; j++) {
                if (j === 1){
                    $(".page-number").append(`<button class="page-btn active" id="${j}">${j}</button>`)
                    continue;
                }
                if (j === 3){
                    $(".page-number").append(`<button class="page-btn" id="${j}">${j}</button>`)
                    $(".page-number").append(`<span>...</span>`)
                    continue;
                }
                $(".page-number").append(`<button class="page-btn" id="${j}">${j}</button>`)
            }
        },
        error:function(){
            alert("查找时获取教案数量失败，请联系管理员")
        }
    })
}

$(".search-btn").on("click",function(){
    getCountWhenSearch()
})

// 生成教案弹层相关基础交互（可根据实际需求完善）
const generateDialog = document.getElementById('generateDialog');
const generateCloseBtn = document.querySelector('.generate-close-btn');
const generateBtn = document.getElementById('generateBtn');
const cancelGenerateBtn = document.getElementById('cancelGenerateBtn');

generateBtn.addEventListener('click', function () {
    generateDialog.style.display = 'flex';
});

generateCloseBtn.addEventListener('click', function () {
    generateDialog.style.display = 'none';
});

cancelGenerateBtn.addEventListener('click', function () {
    generateDialog.style.display = 'none';
});


$(document).ready(function() {
    // 预览弹层相关元素
    const previewDialog = $("#previewDialog");
    const previewCloseBtn = $(".preview-close-btn");
    const cancelPreviewBtn = $("#cancelPreviewBtn");

    // 点击预览按钮显示弹层
    $(".tbody").on("click", ".action-btn[title='预览']", function() {
        previewDialog.css("display", "flex");
        $.ajax({
            url: "/LessonPlanManagement/GetLessonPlanById",
            type: "POST",
            async: false,
            dataType: "json",
            data: {
                id: $(this).data("id")
            },
            success: function(res) {
                const content =res.data.content;
                console.log(content)
                // 模拟AI分析
                document.querySelector(".elegant-report").innerHTML= marked.parse(content.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>'));
            }
        })
    });

    // 关闭预览弹层
    previewCloseBtn.on("click", function() {
        previewDialog.css("display", "none");
    });

    cancelPreviewBtn.on("click", function() {
        previewDialog.css("display", "none");
    });

    // 点击弹层外部关闭
    previewDialog.on("click", function(e) {
        if (e.target === previewDialog[0]) {
            previewDialog.css("display", "none");
        }
    });

    // 生成教案弹层相关交互（你已有部分代码，这里补充完整）
    const generateDialog = $("#generateDialog");
    const generateBtn = $("#generateBtn");
    const generateCloseBtn = $(".generate-close-btn");
    const cancelGenerateBtn = $("#cancelGenerateBtn");

    generateBtn.on("click", function() {
        generateDialog.css("display", "flex");
    });

    generateCloseBtn.on("click", function() {
        generateDialog.css("display", "none");
    });

    cancelGenerateBtn.on("click", function() {
        generateDialog.css("display", "none");
    });

    generateDialog.on("click", function(e) {
        if (e.target === generateDialog[0]) {
            generateDialog.css("display", "none");
        }
    });
});
function showConfirm(message, yesCallback, noCallback) {
    const confirmModal = document.getElementById('confirmModal');
    const confirmContent = document.getElementById('confirmContent');
    const confirmYes = document.getElementById('confirmYes');
    const confirmNo = document.getElementById('confirmNo');
    const closeConfirmModal = document.getElementById('closeConfirmModal');
    // 设置提示内容
    confirmContent.textContent = message;

    console.log(11)
    // 显示模态框
    confirmModal.style.display = 'flex';

    // 设置按钮事件
    confirmYes.onclick = function() {
        confirmModal.style.display = 'none';
        if (yesCallback) yesCallback();
    };

    confirmNo.onclick = function() {
        confirmModal.style.display = 'none';
        if (noCallback) noCallback();
    };

    closeConfirmModal.onclick = function() {
        confirmModal.style.display = 'none';
        // if (noCallback) noCallback();
    };

    // 点击模态框外部关闭
    window.onclick = function(event) {
        if (event.target == confirmModal) {
            confirmModal.style.display = 'none';
        }
    };
}

